package com.health.system.security.auth.filter;

import com.health.system.common.exception.NotJsonFormatException;
import com.health.system.common.utils.JsonUtil;
import com.health.system.common.utils.ServletRequestUtil;
import com.health.system.constant.SecurityConstant;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 登录过滤器
 *
 */
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Setter
    @Getter
    private boolean captchaEnable;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        if (!request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            throw new NotJsonFormatException("请使用JSON格式提交数据");
        }

        try {
            Map<String, String> loginInfo = JsonUtil.convert(request.getInputStream());
            String captcha = loginInfo.get(SecurityConstant.CAPTCHA_KEY);
            if (captchaEnable && !StringUtils.equals(ServletRequestUtil.getAttribute(SecurityConstant.CAPTCHA_KEY), captcha)) {
                throw new AuthenticationServiceException("验证码错误");
            }

            String username = loginInfo.get(getUsernameParameter());
            String password = loginInfo.get(getPasswordParameter());
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (IOException e) {
            throw new AuthenticationServiceException("获取request请求流失败");
        }
    }

}
